﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WPFExcelReport;
using System.Threading;
namespace WPFExcelReport
{
    public partial class WB14IT : Form
    {
        System.Windows.Forms.Timer bTimer;
        public string RUNID = "";
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        string company
        {
            get
            {
                return app.company;
            }
        }
        IF2ITX if2itx;
        public string hwndQI = "", IFQI = "";
        long WINDOW_HANDLER;          // 存放实例1中的WB14IT窗口的窗口句柄    
        IF2MACHINE if2m;
        double FAILS = 999;
        ITXWB itxwb;
        double qty;
        bool IsRun = true;
        public WB14IT()
        {
            InitializeComponent();
            if (app.EnvExe == null)
                app.Load();
            Setup();
        }
        string ARG = "";
        public WB14IT(string[] args)
        {
            app.Load();
            ARG = "";
            foreach (string arg in args)
            {
                ARG += arg + " ";
            }
            InitializeComponent();
            if (app.EnvExe == null)
                app.Load();
            if (args.Length > 0)
            {
                hwndQI = (string)args[2];
                IFQI = (string)args[3];
                WINDOW_HANDLER = Convert.ToInt64(hwndQI);

            }
            else
            {
                if (app.EnvExe.ContainsKey("QITABLE"))
                {
                    hwndQI = app.EnvExe["QITABLE"].ToString();

                }
                else
                {
                    hwndQI = "528044";
                }
                if (app.EnvExe.ContainsKey("QIID"))
                {
                    IFQI = app.EnvExe["QIID"].ToString();
                }
                else
                {
                    IFQI = "0003";
                }
            }
            //MessageBox.Show(hwndQI + "*" + IFQI);
            WINDOW_HANDLER = Convert.ToInt64(hwndQI);
            if (args.Length > 0)
            {
                //MessageBox.Show(args[0]);
            }

            Setup();
        }
        ~WB14IT()
        {
            bTimer.Stop();
        }

        public void Setup()
        {
            /*
            if (app.EnvExe.ContainsKey("START"))
            {
                string date = "", year = "", month = "", day = "";
                WPFExcelReport.Helpers.Helper.GetDate(ref date, ref year, ref month, ref day);
                app.ChgAppSettings("START", date);
            }*/
            if (app.EnvExe.ContainsKey("TERMNO"))
            {
                txtTermNo.Text = app.TERMNO.Trim();
            }
            if (app.EnvExe.ContainsKey("FAILS"))
            {
                FAILS = Convert.ToDouble(app.EnvExe["FAILS"].ToString());
            }
            if (app.EnvExe.ContainsKey("AUTOPRINT"))
            {
                string AUTOPRINT = app.EnvExe["AUTOPRINT"].ToString();
                if (AUTOPRINT == "Y")
                {
                    IsAutoPrint = true;
                    btnAutoPrint.Text = "自动打印Y";
                }
                else
                {
                    IsAutoPrint = false;
                    btnAutoPrint.Text = "自动打印N";
                }
            }
            this.RUNID = "WB13IT";
            bTimer = new System.Windows.Forms.Timer();
            if2m = new IF2MACHINE();
            itxwb = new ITXWB(this.RUNID);
            if2itx = new IF2ITX(WINDOW_HANDLER, IFQI);
            bTimer.Interval = 600;
            bTimer.Tick += bTimer_Tick;
            btnStart.Text = "运行中";
            bTimer.Start();
            this.WindowState = FormWindowState.Minimized;
        }
        private Object thisLock = new Object();
        int fails = 0;
        double lastqty = 0;
        int sames = 0;
        int sends = 0;
        double MTR = 0.0, YD = 0.0;
        void bTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                lock (thisLock)
                {
                    qty = if2m.GetLength();
                    if (qty < 0)//没有成功获取数据
                        return;
                    if (sames > 2 * 60 * 5)
                    {
                        sames = 0;
                        throw new Exception("需要重启启动");
                        /* * //当累积到一定次数后，重新启动程序自己
                        * //记录QI进程号和端口号
                           itxwb.Print();//每隔一定次数连接一下服务器*/

                    }
                    if (lastqty == qty)
                    {
                        sames++;
                        return;
                    }
                    sames = 0;
                    lastqty = qty;
                    textBox1.Text = qty.ToString();
                    /*
                   if (qty < 0)
                   {
                       itxwb.Print();
                       return;
                   }*/
                    if (qty < 5 && app.TERMNO.Trim() == "-1")
                    {
                        itxwb.Print(ref MTR, ref YD);
                        txtMTR.Text = MTR.ToString();
                        txtYD.Text = YD.ToString();
                        return;
                    }
                    if (qty == 0)
                    {
                        //MessageBox.Show("清零");
                        if2itx.SEND2QI(qty);
                        if (IsAutoPrint)
                        {
                            //MessageBox.Show("提交打印");
                            itxwb.Print(ref MTR, ref YD);
                            txtMTR.Text = MTR.ToString();
                            txtYD.Text = YD.ToString();
                        }
                        else
                        {
                            //MessageBox.Show("不需要打印");
                        }
                        return;
                    }
                    IntPtr result = if2itx.SEND2QI(qty);
                    if (result == ((IntPtr)0))
                    {
                        fails++;
                        textFail.Visible = true;
                        textFail.Text = "F:" + fails.ToString();
                    }
                    sends++;
                    if (fails > FAILS)
                    {
                        bTimer.Stop();
                        //throw new Exception("需要重启启动");
                        this.Close();
                        System.Environment.Exit(0);
                    }
                    if (sends > 5)
                    {
                        sends = 0;
                        //throw new Exception("需要重启启动");
                    }
                }
            }
            catch (Exception ex)
            {
                ReStart();
            }
        }


        private void btnSnd2Itnex_Click(object sender, EventArgs e)
        {
            btnStart.Text = "运行中";
            bTimer.Start();
        }
        private void btnStop_Click(object sender, EventArgs e)
        {
            bTimer.Stop();
            btnStart.Text = "启动";
        }
        private void AutoRun(object obj)
        {
            Thread.Sleep(2000);
            System.Diagnostics.Process ps = new System.Diagnostics.Process();
            ps.StartInfo.FileName = obj.ToString();
            ps.StartInfo.Arguments = ARG;
            ps.Start();
        }
        public void ReStart()
        {
            Application.ExitThread();
            Thread tmp = new Thread(new ParameterizedThreadStart(AutoRun));
            object obj = Application.ExecutablePath;
            Thread.Sleep(1);
            tmp.Start(obj);
        }
        private void btnRestart_Click(object sender, EventArgs e)
        {
            ReStart();
        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        bool IsAutoPrint = false;
        private void btnAutoPrint_Click(object sender, EventArgs e)
        {
            if (IsAutoPrint)
            {
                IsAutoPrint = false;
                btnAutoPrint.Text = "自动打印N";
                return;
            }
            IsAutoPrint = true;
            btnAutoPrint.Text = "自动打印Y";
        }

        private void btnRePrint_Click(object sender, EventArgs e)
        {
            itxwb.Print(ref MTR, ref YD, true);
            txtMTR.Text = MTR.ToString();
            txtYD.Text = YD.ToString();
        }

        private void btnNextPrint_Click(object sender, EventArgs e)
        {
            itxwb.Print(ref MTR, ref YD, false);
            txtMTR.Text = MTR.ToString();
            txtYD.Text = YD.ToString();
        }
    }
}
